/** @jsx jsx */
import { jsx, keyframes } from '@emotion/react'
import React, {
    useEffect,
    useLayoutEffect,
    useState,
    useCallback,
    useRef
} from "react";
import { Radio, message, DatePicker, TimePicker, Input, Checkbox, Typography, Select, Collapse, ConfigProvider, Spin, Dropdown } from "antd";
import { connect, useDispatch, useSelector } from "react-redux";
import locale from 'antd/lib/calendar/locale/zh_CN.js'
import axiosMethod from "../../../util/axios";
import { LgSelect, LgTextarea, LgInput, LgDatePicker, LgPaginationA, LgButton } from "lancoo-web-ui";
import CONFIG from "../../../util/config";
import Search from "../../../common/component/search";
import Empty from "../../../common/component/empty";
import { getDateAllGap, getTimeDiff, getQueryVariable } from "../../../util";
import moment from 'moment'
import qs from 'qs'
import md5 from "md5";
import $ from 'jquery'
import CloseIcon from '../../../images/关闭.png'
import styled from "@emotion/styled";
import dayjs from 'dayjs'
import toObject from 'dayjs/plugin/toObject'
import objectSupport from 'dayjs/plugin/objectSupport'
import useGetThem from '../../../hooks/useGetThem';
import "./index.scss";

const {
    appAddr
} = CONFIG;
const { Option } = Select;
const { Text } = Typography
const { RangePicker } = TimePicker;
const { Panel } = Collapse;

function Todo(props) {
    let {
        userInfo,
        currentIdentity,
        isEdu,
        mainServer,
        officeUrl,
        skin
    } = useSelector(state => state);

    const { defaultColor, hoverColor, bgColor, borderColor } = useGetThem(skin)

    const dispatch = useDispatch();
    const [statusList, setStatusList] = useState([
        {
            key: "0",
            name: "进行中"
        },
        {
            key: "1",
            name: "已完成"
        },
        {
            key: "2",
            name: "已逾期"
        }
    ])
    const [typeList, setTypeList] = useState([
    ])
    const [loadVisible, setLoadVisible] = useState(false);
    const [currentStatus, setCurrentStatus] = useState("0");
    const [currentType, setCurrentType] = useState("");
    const [keyword, setKeyword] = useState("");

    const [listTotal, setListTotal] = useState(0);
    const [todoInfo, setTodoInfo] = useState({});
    const [currentIndex, setCurrentIndex] = useState(1);

    const timeSelect = useRef(null)
    // 新建日程
    const [currentTodo, setCurrentTodo] = useState(null)  //当前选中的待办事项
    const [modalVisible, setModalVisible] = useState(false)
    const [modalInfo, setModalInfo] = useState({
        remindFlag: true,
        remindType: 1,
        remindTime: 30,
        repeatTime: 0,
        scheduleDate: moment().format('YYYY-MM-DD'),
    })
    const [modalLoadVisible, setModalLoadVisible] = useState(false);
    const [remindTime, setRemindTime] = useState([
        { key: 0, value: 0, text: "开始时" },
        { key: 5, value: 5, text: "开始前5分钟" },
        { key: 15, value: 15, text: "开始前15分钟" },
        { key: 30, value: 30, text: "开始前30分钟" },
        { key: 60, value: 60, text: "开始前1个小时" },
        { key: 120, value: 120, text: "开始前2个小时" },
    ]);
    const [showMoreSetting, setShowMoreSetting] = useState(false)



    //打开exe客户端
    //initFunc为初始化后的回调函数，成功返回操作对象;失败返回false，表明基础插件不存在
    //操作对象可以调用start(proName, moduleName, url, exeName, exeParam)方法，启动exe
    //操作对象在谷歌火狐及ie10以上浏览器可调用sendmessage(proName, moduleName, msgData)方法，向指定模块发送消息；
    //也可在谷歌火狐及ie10以上浏览器实现reciveExeMessageFunc(msg)函数接收消息
    //当websocket被断开时，将触发reConnectFunc回调函数，此时，可重新建立对象并连接
    function BsToCsFuncAssistantInfoCenter(initFunc, reciveExeMessageFunc, reConnectFunc) {
        this.checkBase = false;
        this._Socket = null;
        this.objState = 0;
        this.objConnect = false;
        this.socketArrayLength = 5;
        this.activexObj = null;

        var maxPort = 15326;
        var browser = getBrowserInfo();

        if (browser != null && browser[0] == "firefox") {
            //this.socketArrayLength = 2;
            //maxPort = 15323;
        }

        var socketArray = new Array();
        var thisObj = this;

        for (var i = 15321; i < maxPort; ++i) {
            try {
                var tmpSocket = new WebSocket("ws://127.0.0.1:" + i);
                //tmpSocket.CONNECTING
                socketArray.push(tmpSocket);

                tmpSocket.onclose = function () {
                    if (!thisObj.checkBase) {
                        --thisObj.socketArrayLength;

                        if (thisObj.socketArrayLength <= 0) {
                            if (typeof initFunc == 'function') {
                                initFunc(false);
                            }
                        }
                    }

                    else {

                        //说明本来连接到了socket服务器，但是突然断开了，最有可能是因为服务被停止了，以及卸载或重装了基础插件
                        if (typeof reConnectFunc == 'function') {
                            reConnectFunc();
                        }
                    }
                }

                    ;

                tmpSocket.onopen = function () {
                    switch (this.readyState) {
                        case 0:
                        case 2: case 3: break;
                        case 1:
                            thisObj.objState = 0;
                            thisObj.objConnect = true;
                            thisObj._Socket = this;
                            thisObj.checkBase = true;

                            if (typeof initFunc == 'function') {
                                initFunc(thisObj);
                            }

                            if (typeof reciveExeMessageFunc == 'function') {
                                this.onmessage = function (e) {
                                    reciveExeMessageFunc(e.data);
                                }
                            }

                            break;
                    }
                }
            }

            catch (e) {
                try {
                    thisObj.objState = 1;
                    thisObj.objConnect = true;
                    createActivexObj("B94EBF17-D4AB-4A91-A298-008DDA8AEFB3", "LgClientStart", "", 1, 1);
                    thisObj.activexObj = document.getElementById("LgClientStart");

                    if (thisObj.activexObj.CheckOcx() == "ok") {
                        thisObj.objConnect = true;
                        thisObj.checkBase = true;

                        if (typeof initFunc == 'function') {
                            initFunc(thisObj);
                        }
                    }

                    else {
                        if (typeof initFunc == 'function') {
                            initFunc(false);
                        }
                    }
                }

                catch (e) {
                    if (typeof initFunc == 'function') {
                        initFunc(false);
                    }
                }

                break;
            }
        }

    }

    BsToCsFuncAssistantInfoCenter.prototype.start = function (proName, moduleName, url, exeName, exeParam) {
        if (this.objState == 0) {
            if (this.objConnect) {
                var char1 = String.fromCharCode(1);
                var char2 = String.fromCharCode(2);
                //连接成功后
                this._Socket.send(proName + char1 + moduleName + char1 + "001" + char2 + url + char2 + exeName + char2 + exeParam);
                return true;
            }

            else {
                return false;
            }
        }

        else {
            if (this.objConnect) {
                this.activexObj.NotifyService("5$" + url + "," + proName + "," + moduleName + "," + exeName + "#" + exeParam);
                return true;
            }

            else {
                return false;
            }
        }
    }

    //如果页面需要接收exe发送的消息，则需要在initFunc函数内调用此函数
    BsToCsFuncAssistantInfoCenter.prototype.willReciveMessage = function (proName, moduleName) {
        if (this.objState == 0) {
            if (this.objConnect) {
                var char1 = String.fromCharCode(1);
                var char2 = String.fromCharCode(2);
                this._Socket.send(proName + char1 + moduleName);
                return true;
            }
        }

        return false;
    }

    BsToCsFuncAssistantInfoCenter.prototype.sendMessage = function (proName, moduleName, msgData) {
        if (this.objState == 0) {
            if (this.objConnect) {
                var char1 = String.fromCharCode(1);
                var char2 = String.fromCharCode(2);
                //给exe发信息
                this._Socket.send(proName + char1 + moduleName + char1 + "000" + char2 + msgData);
                return true;
            }
        }

        return false;
    }

    //如果页面需要获取本机mac地址，则需要在initFunc函数内调用此函数，将在reciveExeMessageFunc内接收到{LocalMacIDs:[mac1,mac2,...,macN]}的json字符串
    BsToCsFuncAssistantInfoCenter.prototype.GetMacIDs = function (proName, moduleName) {
        if (this.objState == 0) {
            if (this.objConnect) {
                var char1 = String.fromCharCode(1);
                var char2 = String.fromCharCode(2);
                //给服务发信息
                this._Socket.send(proName + char1 + moduleName + char1 + "002" + char2 + "");
                return true;
            }
        }

        return false;
    }

    //检测浏览器类型及版本
    function getBrowserInfo() {
        var Sys = {}

            ;
        var ua = navigator.userAgent.toLowerCase();
        var s;
        var res = new Array();
        // (s = ua.match(/msie ([\d.]+)/)) ? Sys.ie = s[1] : (s = ua.match(/firefox\/([\d.]+)/)) ? Sys.firefox = s[1] : (s = ua.match(/chrome\/([\d.]+)/)) ? Sys.chrome = s[1] : (s = ua.match(/opera\/([\d.]+)/)) ? Sys.opera = s[1] : (s = ua.match(/version\/([\d.]+).*safari/)) ? Sys.safari = s[1] : 0;

        if (Sys.ie) {
            res[0] = "ie";
            res[1] = Sys.ie;
        }

        else if (! !window.ActiveXObject || "ActiveXObject" in window) {
            res[0] = "ie";
            res[1] = "11.0";
        }

        else if (Sys.firefox) {
            res[0] = "firefox";
            res[1] = Sys.firefox;
        }

        else if (Sys.chrome) {
            res[0] = "chrome";
            res[1] = Sys.chrome;
        }

        else if (Sys.safari) {
            res[0] = "safari";
            res[1] = Sys.safari;
        }

        else if (Sys.opera) {
            res[0] = "opera";
            res[1] = Sys.opera;
        }

        else {
            res = null;
        }

        return res;
    }

    //---------------------浏览器兼容Begin-----------------------------//
    //创建ActiveX控件实例
    function createActivexObj(clsid, objID, evtArr, width, height) {
        if (document.getElementById(objID) == null) {
            var browserInfo = getBrowserInfo();
            var AcXobj;

            if (browserInfo[0] == "ie") {
                AcXobj = document.createElement("OBJECT");
                AcXobj.setAttribute("classid", "clsid:{" + clsid + "}");

                if (evtArr) {
                    for (var i = 0; i < evtArr.length; i++) {
                        var evts = evtArr[i].split(":");
                        document.body.innerHTML += ('<script for="' + objID + '" event="' + evts[0] + '(' + setArgs(evts[2]) + ')">' + evts[1] + '(' + setArgs(evts[2]) + ');</script>');
                    }
                }
            }

            AcXobj.setAttribute("id", objID);

            if (width == null || height == null || width == 0 || height == 0) {
                AcXobj.setAttribute("height", 0);
                AcXobj.setAttribute("width", 0);

                if (browserInfo[0] == "ie" && (browserInfo[1] == "6.0" || browserInfo[1] == "7.0")) {
                    AcXobj.style.display = "none";
                }
            }

            else {
                AcXobj.setAttribute("height", height);
                AcXobj.setAttribute("width", width);
            }

            document.body.appendChild(AcXobj);
        }

        function setArgs(alenght) {
            if (alenght == null) return "";
            var res = "";

            for (var ai = 0; ai < alenght; ai++) {
                res += "acxArg_" + ai + ",";
            }

            res = res.substr(0, res.length - 1);
            return res;
        }
    }

    //---------------------浏览器兼容End-----------------------------//
    function getStartPorotol(AccessParam, it, type) {
        // if(type === "out"){
        //   this.state.Bs2Cs.start(AccessParam.proName, AccessParam.moduleName, AccessParam.BasicWebUrl, AccessParam.exeName, AccessParam.exeParam);
        //   return;
        // }
        var lg_ic = getQueryVariable('lg_ic')

        var lg_tk = sessionStorage.getItem('token');
        var BasicWebRootUrl = window._BasicProxy
        var UserID = userInfo.UserID
        var UserName = userInfo.UserName
        var SchoolID = userInfo.SchoolID
        AccessParam = AccessParam.replace(/{token}/, lg_tk);
        AccessParam = AccessParam.replace(/{lg_ic}/, lg_ic);
        AccessParam = AccessParam.replace(/{identitycode}/, lg_ic);
        AccessParam = AccessParam.replace(/{userid}/, UserID);
        AccessParam = AccessParam.replace(/{username}/, UserName);
        AccessParam = AccessParam.replace(/{MainServerAddr}/, BasicWebRootUrl);
        AccessParam = AccessParam.replace(/{ServerAddr}/, it.WebSvrAddr);
        AccessParam = AccessParam.replace(/{schoolid}/, SchoolID);

        // SaveEntranceAccessBehaviorRecordFn(item)
        if (AccessParam.slice(0, 9) !== 'lgsoft://') {
            window.open(AccessParam, "_blank");
            return
        }


        AccessParam = AccessParam.replace(/{MainServerAddrNoHttp}/, BasicWebRootUrl.slice(7, BasicWebRootUrl.length - 1));
        if (_clientObj) {

            const proName = AccessParam.split('::')[0].split('://')[1];

            const moduleName = AccessParam.split('::')[1];

            const exeName = AccessParam.split('::')[2];


            const BasicWebUrl = sessionStorage.getItem("PsnMgrMainServerAddr");

            // MainServerAddrNoHttp
            const token = sessionStorage.getItem('PsnMgrToken');
            var porotol = AccessParam.split('::')[3].replace(/{MainServerAddr}/g, BasicWebUrl).replace(/{token}/g, token);

            if (porotol.indexOf("Convert.ToBase64String(") > -1) {

                porotol = "://" + window.btoa(encodeURIComponent(porotol.slice(23, -1)));

            }

            console.log(proName, moduleName, BasicWebUrl, exeName, porotol);
            _clientObj.start(proName, moduleName, BasicWebUrl, exeName, porotol);

        }

    }

    var _clientObj = new BsToCsFuncAssistantInfoCenter(InitFunc);
    var _clientFlag = true;

    function InitFunc(param) {
        if (!param) {
            _clientFlag = false;
        }
    }

    function commonOpenClient(porotol, it) {
        console.log(porotol, it)
        if (!_clientFlag) {
            alert('您还未安装基础插件包，请先下载和安装插件包！')
        } else {
            setTimeout(function () {
                getStartPorotol(porotol, it)
            }, 100);
        }
    }
    const showMeSchedule = (data) => {
        window.getWebAddr('260', function (officeUrl) {
            axiosMethod({
                url: officeUrl + '/api/schedule/info/detail',
                body: {
                    userId: userInfo.UserID,
                    userType: 0,
                    schoolId: userInfo.SchoolID,
                    scheduleId: data.msgId
                },
                callback: function (res) {
                    axiosMethod({
                        type: 'post',
                        url: officeUrl + '/api/schedule/member/update/attend',
                        body: {
                            "userId": userInfo.UserID,
                            "scheduleId": data.msgId,
                            "schoolId": userInfo.SchoolID,
                            "attendFlag": 1
                        },
                    })
                    dispatch({
                        type: "SET_SCHEDULEINFO",
                        data: {
                            visible: true,
                            scheduleObj: res,
                            onConfirm: (State) => {

                                if (State == 2 || State == 3) {
                                    if (State == 2 && userInfo.UserID !== data.userId) {
                                        axiosMethod({
                                            type: "POST",
                                            url: officeUrl + '/api/schedule/created/save',
                                            body: {
                                                "userId": userInfo.UserID,
                                                "userType": userInfo.UserType,
                                                "userName": userInfo.UserName,
                                                "schoolId": userInfo.SchoolID,
                                                "scheduleDate": res.scheduleDate,
                                                // "scheduleEndDate": res?.scheduleEndDate || res.scheduleDate,
                                                "startTime": res.startTime,
                                                "endTime": res.endTime,
                                                "beAllDay": res?.beAllDay || 0,
                                                "scheduleTitle": res.scheduleTitle,
                                                "scheduleContent": res.scheduleContent,
                                                "scheduleLocation": res.scheduleLocation,
                                                "remindFlag": 1,
                                                "remindTime": res?.remindTime,
                                                "remindRealTime": `${res.scheduleDate} ${res.startTime}:00`,
                                                "repeatTime": 0,
                                                "repeatTimeList": res?.repeatTimeList || [0],
                                                "beExternal": 1,
                                                "meetingScheduleId": res.scheduleId,
                                                "beMeeting": 1,
                                                "termStartDate": userInfo.termStartDate,
                                                "termEndDate": userInfo.termEndDate,
                                                "scheduleMemberBoList": res.scheduleMemberBoList
                                            },
                                            callback: function () {  //成功更新状态为已拒绝或
                                            }
                                        })
                                    }
                                    axiosMethod({
                                        type: 'POST',
                                        url: officeUrl + '/api/schedule/member/update/attend',
                                        body: {
                                            "userId": userInfo.UserID,
                                            "scheduleId": data.msgId,
                                            "schoolId": userInfo.SchoolID,
                                            "attendFlag": State
                                        },
                                        callback: () => {
                                            axiosMethod({  //清除该代办
                                                url: '/api/todo/manage/update/status',
                                                type: 'PUT',
                                                body: {
                                                    userId: userInfo.UserID,
                                                    schoolId: userInfo.SchoolID,
                                                    todoMsgId: data.todoMsgId,
                                                    status: 1
                                                },
                                                callback: () => {
                                                    dispatch({
                                                        type: 'SET_SCHEDULEINFO',
                                                        data: {
                                                            visible: false
                                                        }
                                                    })
                                                    getList()
                                                    message.success('操作成功')
                                                }
                                            })
                                        }
                                    })
                                }
                            },
                        }
                    })
                }
            })
        })
    }

    const changeStatus = useCallback((data) => {
        setCurrentIndex(1)
        setCurrentStatus(data.key);
    }, []);
    const changeType = useCallback((data) => {
        setCurrentIndex(1)
        setCurrentType(data);
    }, []);
    const getList = useCallback((pageIndex = currentIndex) => {
        setLoadVisible(true);
        if (keyword) {
            pageIndex = 1
        }
        axiosMethod({
            type: "get",
            url: "/api/todo/list/getPageList",
            body: {
                pageIndex: 1,
                pageSize: 9999,
                keyWord: keyword,
                status: currentStatus,
                userId: userInfo.UserID,
                userType: userInfo.UserType,
                schoolId: userInfo.SchoolID,
                msgSourceId: currentType.msgSourceId
            },
            isBackAll: true,
            callback: function (res) {
                let realCount = 0, realTodoList = [], dealTodoList = [];
                let noticeList = res.data
                noticeList.map(function (item, idx) {
                    if (item.receiverType == 0 || item.receiverType == 1 || item.receiverType == 4 || item.receiverType == 5) {
                        realCount++;
                        realTodoList.push(item)
                    }
                })

                if (pageIndex > 1 && realTodoList.length > 0) {
                    dealTodoList = realTodoList.slice((pageIndex - 1) * 12, pageIndex * 12)
                } else {
                    dealTodoList = realTodoList.slice(0, 12)
                }

                setTodoInfo(dealTodoList);
                setListTotal(realCount)
                setLoadVisible(false);
            }
        });
    }, [userInfo, currentIndex, currentType, keyword, currentStatus]);

    const getTypeList = useCallback(() => {
        axiosMethod({
            type: "get",
            url: "/api/message/type/list",
            body: {
                schoolId: userInfo.SchoolID,
                userId: userInfo.UserID,
                type: 2,
                userType: userInfo.UserType,
                environment:isEdu?1:2
            },
            callback: function (res) {
                let typeArr = res.messageSourceList
                typeArr.length > 0 && typeArr.forEach(item => {
                    item.text = item.msgSourceName
                });
                typeArr.unshift({
                    text: '全部',
                    msgSourceName: '全部',
                    msgSourceId: ''
                })
                setCurrentType(res?.messageSourceList[0] ? res?.messageSourceList[0].msgSourceId : "");

                setTypeList(typeArr);
            }
        });
    }, [userInfo]);

    const searchMethod = useCallback((value) => {  //搜索函数
        setKeyword(value);
        // if (currentIndex === 1) {
        //     getList();
        // } else {
        //     setCurrentIndex(1);
        // }
    }, [getList])

    var refuseReason = ''
    const showMeAssignment = (todo) => {
        setLoadVisible(true)
        var isRemindPublisher = true
        let taskId=todo.msgId.slice(0,19)
        window.getWebAddr('260', function (officeUrl) {
            //已读任务
            axiosMethod({
                url: officeUrl + '/api/task/user/read',
                type: 'put',
                body: {
                    userId: userInfo.UserID,
                    taskId
                }
            })
            axiosMethod({
                url: officeUrl + '/api/task/info/detail',
                type: 'get',
                body: {
                    userId: userInfo.UserID,
                    taskId,
                },
                callback: function (data) {
                    setLoadVisible(false)
                    var assignmentObj = data

                    var title = assignmentObj.title
                    var userName = assignmentObj.userName
                    var userId = assignmentObj.userId
                    var time = assignmentObj.startTime.replace(/-/g, '/').substring(0, 16) + '~' + assignmentObj.endTime.replace(/-/g, '/').substring(0, 16)
                    var remark = assignmentObj.remark || '--'
                    var avatar = assignmentObj.avatarPath ? 'url(' + assignmentObj.avatarPath + ')' : ''

                    var assignmentPop = $('<div class="assignment_pop"><div class="assignment_card"><div class="reason_box"><i class="reason_close"></i><p>任务拒绝原因</p><textArea maxlength="80" class="reason_text" placeholder="请在此输入原因..."></textArea><div class="reason_check"><input checked class="isRemind" type="checkbox"></input><span>给发布者<i>(' + userName + ')</i>发送拒绝原因的消息提醒</span></div><div class="reason_footer"><span class="reason_confirm">确认</span><span class="reason_cancel">取消</span></div></div><i class="assignment_close"></i><p class="title">任务领取</p><div class="content_box"><p class="assignment_type" title=' + title + '>' + title + '</p><p><span class="left title2">发布者：</span><span class="assignment-originator-avatar" style="background-image:' + avatar + '"></span><span class="assignment-originator-name">' + userName + '</span><span class="assignment-originator-id">(' + userId + ')</span></p><p><span class="left title3">时限：</span><span class="assignment-time">' + time + '</span></p><p class="assignment_remark"><span class="left title5">任务说明：</span><span class="assignment_content" title=' + remark + '>' + remark + '</span></p></div><div class="assignment_footer"><span class="assignment_yes">接受任务</span><span class="assignment_no">拒绝任务</span><span class="assignment_wait">暂不响应</span></div></div></div>')
                    $('.app_main').append(assignmentPop)

                    $('.assignment_close').off().click(function () {
                        $('.assignment_pop').hide()
                    })

                    $('.reason_close').off().click(function () {
                        $('.reason_box').hide()
                    })

                    $('.reason_text').keyup(function (e) {
                        refuseReason = e.target.value
                    })

                    $('.assignment_yes').off().click(function () {
                        axiosMethod({
                            url: officeUrl + 'api/task/user/accept_refuse',
                            type: 'PUT',
                            body: {
                                taskId,
                                userId: userInfo.UserID,
                                userName: userInfo.UserName,
                                progress: 1,
                                refuseRemark: '',
                                pushMsg: 0,
                            },
                            callback: function () {
                                axiosMethod({
                                    url: '/api/todo/manage/update/status',
                                    type: 'PUT',
                                    body: {
                                        userId: userInfo.UserID,
                                        schoolId: userInfo.SchoolID,
                                        todoMsgId: todo.todoMsgId,
                                        status: 1
                                    },
                                    callback: function () {
                                        getList()
                                    }
                                })
                                message.success('操作成功')
                                $('.assignment_pop').hide()
                            }
                        })
                    })

                    $('.assignment_no').off().click(function () {
                        $('.reason_box').show()
                    })

                    $('.reason_confirm').off().click(function () {
                        isRemindPublisher = $('.reason_check input:checked').val() === 'on' ? 1 : 0


                        if (!refuseReason) {
                            message.warn('请输入拒绝原因')
                            return
                        }
                        axiosMethod({
                            url: officeUrl + 'api/task/user/accept_refuse',
                            type: 'PUT',
                            body: {
                                taskId,
                                userId: userInfo.UserID,
                                userName: userInfo.UserName,
                                progress: '3',
                                refuseRemark: refuseReason,
                                pushMsg: isRemindPublisher,
                            },
                            callback: function () {
                                message.success('操作成功')
                                $('.assignment_pop').hide()
                                axiosMethod({
                                    url: '/api/todo/manage/update/status',
                                    type: 'PUT',
                                    body: {
                                        userId: userInfo.UserID,
                                        schoolId: userInfo.SchoolID,
                                        todoMsgId: todo.todoMsgId,
                                        status: 1
                                    },
                                    callback: function () {
                                        getList()
                                    }
                                })
                            }
                        })
                    })

                    $('.reason_cancel').off().click(function () {
                        $('.reason_box').hide()
                    })


                    $('.assignment_wait').off().click(function () {
                        $('.assignment_pop').hide()
                    })
                }
            })
        })
    }

    function createPopUp(attrList, infoObj, optionList, extraDate = {}, parentDom = '.popup-main') {
        /* attrList第一项为待办事件名 第二项为内容标题名 后面为内容标题名 */
        var userName = infoObj?.userName || '--'
        var userId = infoObj?.userId || '--'
        var avatar = infoObj.avatar ? 'url(' + infoObj.avatar + ')' : ''
        var contentDom = ''
        attrList.forEach(function (item, index) {
            if (index > 1) {
                if (item.key === 'userName') {
                    contentDom += '<p class="content-row"><span class="left">' + item.title + '</span><span class="right"><i class="avatar"></i><span class="userName" title="' + userName + '">' + userName + '</span><span class="userId" title="' + userId + '">(' + userId + ')</span></span></span></p>'
                } else {
                    contentDom += '<p class="content-row"><span class="left">' + item.title + '</span><span class="right" title="' + infoObj[item.key] + '">' + infoObj[item.key] + '</span></p>'
                }
            }
        })

        var optionDom = ''
        Array.isArray(optionList) && optionList.forEach(function (item, index) {
            optionDom += '<span class="btn ' + item.key + '" data-state="' + item.state + '">' + item.text + '</span>'
        })




        var sourceName = '--'
        var title = '--'
        if (attrList[0]) {
            sourceName = attrList[0]
        }
        if (attrList[1]) {
            title = attrList[1]
        }
        if (attrList.length <= 2) {
            return
        }


        var popupDom = $('<div class="custom-popup"><div class="popup-card"><i class="close-btn"></i><p class="title">' + sourceName + '</p><div class="content-box"><p class="content-title" title="' + title + '">' + title + '</p>' + contentDom + '</div><div class="custom-footer">' + optionDom + '</div></div></div>')

        $(parentDom).append(popupDom)

        $('.custom-popup .close-btn').click(function () {
            $('.custom-popup').hide()
        })

        $('.custom-popup .confirm').off().click(function () {
            if (optionList && optionList[0]) {
                typeof optionList[0].callback === 'function' && optionList[0].callback($(this).attr('data-state'), extraDate)
            }
        })

        $('.custom-popup .refuse').off().click(function () {
            if (optionList && optionList[1]) {
                typeof optionList[1].callback === 'function' && optionList[1].callback($(this).attr('data-state'), extraDate)
            }
        })

        $('.custom-popup .wait').off().click(function () {
            if (optionList && optionList[2]) {
                typeof optionList[2].callback === 'function' && optionList[2].callback($(this).attr('data-state'), extraDate)
            }
        })
    }

    function handleTodoUpdate(extraData) {
        axiosMethod({
            url: '/api/todo/manage/update/status',
            type: 'put',
            body: {
                userId: userInfo.UserID,
                schoolId: userInfo.SchoolID,
                todoMsgId: extraData.todoInfo.todoMsgId,
                status: 1
            },
            callback: function (data) {
                $('.custom-popup').hide()
                getList()
                message.success('操作成功')
            }
        })
    }

    function handleActive(state, extraData) {
        axiosMethod({
            url: mainServer + '/SysMgr/Setting/Holiday/SetActivityUserStatus',
            type: 'post',
            body: {
                appid: '210',
                access_token: md5('210').split('').reverse().join(''),
                activityID: extraData.activityID,
                userID: userInfo.UserID,
                status: state
            },
            header: {
                Authorization: 'X-Token=' + getQueryVariable('lg_tk')
            },
            callback: function (data) {
                if (state == 1 || state == 2) {
                    handleTodoUpdate(extraData)
                } else {
                    $('.custom-popup').hide()
                    getList()
                    message.success('操作成功')
                }
            }
        })
    }

    const showMeActive = (data) => {
        axiosMethod({
            url: mainServer + '/SysMgr/Setting/Holiday/GetActivityByMsgID',
            body: {
                appid: '210',
                access_token: md5('210').split('').reverse().join(''),
                msgID: data.msgId
            },
            header: {
                Authorization: 'X-Token=' + getQueryVariable('lg_tk')
            },
            isBackAll: true,
            callback: function (result) {
                let activtyInfo = result.Data
                activtyInfo.date = activtyInfo.StartDate.replace(/-/g, '/') + '~' + activtyInfo.EndDate.replace(/-/g, '/')
                activtyInfo.userName = activtyInfo.UserName
                activtyInfo.userId = activtyInfo.UserID
                let activeName = activtyInfo.ActivityName
                let title = activtyInfo.ActivityTypeName
                let attrList = [
                    title,
                    activeName,
                    { key: 'userName', title: '发起人：' },
                    { key: 'date', title: '活动时间：' },
                    { key: 'ActivityPosition', title: '活动地点：' }
                ]
                let optionList = [
                    { key: 'confirm', text: '确认参加', state: '1', callback: handleActive },
                    { key: 'refuse', text: '拒绝参加', state: '2', callback: handleActive },
                    { key: 'wait', text: '待定', state: '3', callback: handleActive }
                ]
                let extraDate = { activityID: activtyInfo.ActivityID, todoInfo: data }
                createPopUp(attrList, activtyInfo, optionList, extraDate, '.app_main')
            }
        })
    }

    const todoClick = useCallback((data) => {

        if (data.pcLinkType === '1') {
            if (!data.pcLink) {
                return
            }
            window.getWebAddr(data.sysId, function (webAddr) {
                let url = data.pcLink
                    .replace("[token]", sessionStorage.getItem("token"))
                    .replace("[IdentityCode]", currentIdentity.identityCode);
                window.open(webAddr + url);
            })
        } else if (data.pcLinkType === '2') {
            window.getWebAddr(data.sysId, function (webAddr) {
                let url = data.pcLink
                commonOpenClient(url, { WebSvrAddr: webAddr })
            })
        } else if (data.pcLinkType === '3') {
            if (!data.pcLink) {
                return
            }
            window.open(data.pcLink.replace("[token]", sessionStorage.getItem("token")).replace("[IdentityCode]", currentIdentity.identityCode), '_blank')
        } else if (data.pcLinkType === '4') {
            if (data.templateId === '26003') {
                showMeAssignment(data)
            } else if (data.templateId === '20002') {
                showMeSchedule(data)
            } else if (data.templateId === '00027') {
                showMeActive(data)
            }
        }
    }, []);

    const createSchedule = (e, item, value) => {
        e && e.stopPropagation();

        setCurrentTodo(item)
        setModalVisible(true)
        setModalInfo({
            remindTime: { value: 30, text: '开始前30分钟' },
            scheduleTitle: item.msgSourceName,
            scheduleContent: item.msgPushContent,
            scheduleDate: moment().format("YYYY-MM-DD"),
            startTime: getDataInt(),
            endTime: getDataInt(2),
            scheduleId: item.msgPushId,
            multipleStartTime: `${moment().format("YYYY-MM-DD")} ${getDataInt()}`,
            multipleEndTime: `${moment().format("YYYY-MM-DD")} ${getDataInt(2)}`,
            scheduleLocation: ''
        });
    }

    const modalChange = useCallback((value) => {   //控制日程弹窗显隐
        setModalVisible(value);
        if (!value) {
            setModalInfo({
                remindFlag: false,
                remindType: 1,
                remindTime: 30,
                repeatTime: 0,

            });
        }
    }, []);

    const editModalInfo = useCallback((type, value, reset = false) => {  //修改新建/编辑日程数据
        let info = JSON.parse(JSON.stringify(modalInfo));

        // console.log(type, value,reset)
        if (type === "scheduleDate") {
            value = value.format("YYYY-MM-DD");
            // value = value.map(item=>moment(item).format("YYYY/MM/DD HH:mm"));
        }
        if (type === "scheduleTime") {
            console.log(value)
            if (!info.scheduleDate) {
                message.warn("请先选择日期");
                return;
            }
            value = value.map(item => item.format("HH:mm"));
            info["startTime"] = value[0];
            info["endTime"] = value[1];
            // value = value.map(item=>item.format("YYYY/MM/DD HH:mm"));
        }

        if(type=='startTime'){
            info['endTime']=getDataInt(2,value,true)
        }

        if (type === "remindFlag") {
            // if(value){
            //     info["remindTime"] = 0;
            // }
        }
        if (type === "remindType") {
            if (String(value) === "0") {
                info["remindTime"] = 0;
            }
        }
        if (type === "remindTime") {
            // value = value > 999 ? 999 : value;
        }
        info[type] = value;
        console.log(info)
        setModalInfo(info);
    }, [modalInfo]);

    const operateSchedule = useCallback((data, type, allOrOneFlag) => {  //操作日程
        axiosMethod({
            type: "post",
            url: officeUrl + "/api/schedule/foreign/save",
            body: {
                "sysId": currentTodo.sysId,
                "secCode": md5(currentTodo.sysId).split('').reverse().join(''),
                "scheduleList": [
                    {
                        "scheduleId": currentTodo.msgPushId,
                        "eduId": userInfo.SchoolID,
                        "scheduleDate": modalInfo.scheduleDate,
                        "startTime": modalInfo.startTime,
                        "endTime": modalInfo.endTime,
                        // "multipleStartTime":`${modalInfo.scheduleDate} ${modalInfo.startTime}`,
                        // "multipleEndTime":`${modalInfo.scheduleDate} ${modalInfo.endTime}`,
                        "scheduleTitle": modalInfo.scheduleTitle,
                        "scheduleContent": modalInfo.scheduleContent,
                        "scheduleLocation": modalInfo.scheduleLocation,
                        "remindTime": modalInfo.remindTime.value || 30,
                        "receivers": `${userInfo.UserID}`,
                    }
                ]
            },
            callback: function (res) {
                setModalLoadVisible(false);
                message.success('加入日程成功')
                axiosMethod({
                    type: 'PUT',
                    url: '/api/todo/manage/update/isSchedule',
                    body: {
                        userId: userInfo.UserID,
                        schoolId: userInfo.SchoolID,
                        todoMsgId: currentTodo.todoMsgId,
                        isSchedule: 1,
                    },
                    callback: () => {
                        getList()
                    }
                })
                modalChange(false);
            }
        });

    }, [modalChange, currentTodo, officeUrl, getList, modalInfo, userInfo]);

    const handleSchedule = useCallback(() => {
        if (!modalInfo.scheduleTitle) {
            message.warn("日程标题不能为空");
            return;
        }
        if (!modalInfo.scheduleDate) {
            message.warn("日期不能为空");
            return;
        }
        if (!modalInfo.startTime || !modalInfo.endTime) {
            message.warn("时间不能为空");
            return;
        }
        if (modalInfo.startTime === modalInfo.endTime) {
            message.warn('时间间隔不能为0')
            return
        }
        operateSchedule(modalInfo);
    }, [modalInfo]);

    const setRemindHandle = (item) => {
        editModalInfo('remindTime', item)
    }

    const getDataInt = (num = 1, value = dayjs().format('HH:mm'), isReset = false) => {
        dayjs.extend(objectSupport)
        dayjs.extend(toObject)
        let dataObj = dayjs().toObject()
        if (num === 2) {
            dataObj = dayjs(`${modalInfo.scheduleDate} ${value}`).toObject()
        }
        dataObj.hours += isReset ? 1 : num
        dataObj.minutes =isReset?dataObj.minutes:0
        dataObj.seconds = 0
        return dayjs(dataObj).format('HH:mm')
    }

    useEffect(() => {
        getDataInt()
        getList();
    }, [getList, currentIndex, currentType, keyword]);
    useEffect(() => {
        getTypeList();
    }, [getTypeList]);

    useLayoutEffect(() => {
        let pot1 = window.location.href.indexOf('?')
        let pot2 = window.location.href.lastIndexOf('#')
        let routerStr = window.location.href.substring(pot1, pot2)
        let routerParams = qs.parse(routerStr)
        const { type, sysId, msgPushId } = routerParams
        let todoItem = {}
        let addSchedlueInfo = JSON.parse(sessionStorage.getItem('addScheduleInfo')) || {}
        if (msgPushId && Array.isArray(todoInfo) && todoInfo.length > 0 && !window.isFirst) {
            todoInfo.forEach(item => {
                if (item.msgPushId === msgPushId) {
                    setCurrentTodo(item)
                    todoItem = item
                    window.isFirst = true
                }
            })
            console.log(addSchedlueInfo)
            if (addSchedlueInfo && addSchedlueInfo.msgPushId && addSchedlueInfo.msgPushId === msgPushId) {
                todoItem = addSchedlueInfo
                window.isFirst = true
                setCurrentTodo(addSchedlueInfo)
            }

            if (JSON.stringify(todoItem) === '{}' || todoItem.isSchedule == 1) {
                return
            }


            setTimeout(() => {
                createSchedule('', todoItem, true)
            }, 500);
        }
    }, [todoInfo])

    return (
        <div className='main_todo'>
            <Spin spinning={loadVisible} tip="加载中...">
                <div className="todo_option">
                    {
                        statusList.map((item, index) => (
                            <span
                                className={`option_one`}
                                css={{
                                    color: item.key === currentStatus ? defaultColor : '',
                                    borderColor: `${borderColor}!important`,
                                    backgroundColor: item.key === currentStatus ? bgColor : '',
                                    '&:hover': {
                                        color: hoverColor,
                                    }
                                }}
                                onClick={() => changeStatus(item)}
                                key={index}>{item.name}</span>
                        ))
                    }
                    <span className="slice_line"></span>
                    <div className="g005-SelectA1 option_select">
                        <LgSelect
                            datalist={typeList}
                            SelectOption={(item) => { changeType(item) }}
                            value={currentType.text || '全部分类'}
                            placeholder={'全部'}
                            size={"normal"}

                        ></LgSelect>

                    </div>
                    <span className="list_info">共<span>{listTotal}</span>条</span>
                    <Search className="option_search" searchMethod={searchMethod} placeholder="搜索消息内容..." />
                </div>
                <div className="todo_list">
                    {
                        Array.isArray(todoInfo) &&
                            todoInfo.length > 0 ?
                            todoInfo.map((item, index) => (
                                <div className="todo_one" key={index} onClick={() => todoClick(item)}>
                                    <div className="todo_left">
                                        <i className={`todo_icon ${item.msgSourceName === '课前预习' ?
                                            'todo_type2' :
                                            item.msgSourceName === '课外计划' ?
                                                'todo_type3' :
                                                item.msgSourceName === '课后作业' ?
                                                    'todo_type1' :
                                                    'todo_type4'
                                            }`}></i>
                                        <div className="one_info">
                                            <h4 className="info_type">
                                                {item.msgSourceName}
                                            </h4>
                                            <p className="info_content" title={item.msgPushContent}>
                                                <span className="text">{item.msgPushContent}</span>
                                            </p>
                                            <span className="gap_time" style={{ display: getDateAllGap(item.msgPushExpire, "") ? '' : 'none' }}>
                                                {getDateAllGap(item.msgPushExpire, "") ? getDateAllGap(item.msgPushExpire, "") + "截止" : ""}
                                            </span>
                                            <span className="add_schedule_option">
                                                {
                                                    item.templateId != '20002' && item.templateId != '26002' && item.templateId != '26003' && item.templateId != '00027' && currentStatus == 0 ?
                                                        (item.isSchedule == 1 ?
                                                            <span className="already_add">已加入日程</span>
                                                            :
                                                            <span
                                                                className="add_schedule_btn"
                                                                onClick={(e) => createSchedule(e, item, true)}
                                                                id={item.InfoID}><i className="add_icon"></i>加入日程</span>) : ""

                                                }
                                            </span>
                                        </div>
                                    </div>
                                    <div className="todo_right">
                                        <Text
                                            style={{ maxWidth: '80px', color: 'inherit' }}
                                            ellipsis={true}
                                            title={item.userName}
                                        >
                                            {item.userName}
                                        </Text>
                                        <span></span>
                                        <span className="info_time">{item.msgPushTime && getTimeDiff(item.msgPushTime) || '刚刚'}</span>
                                    </div>

                                </div>
                            )) :
                            <Empty text={'暂无待办事项'} style={{ marginTop: 160 }} />
                    }
                </div>
                <div className="todo_footer">
                    <div className="lg-skin-s2" style={{ display: `${listTotal > 12 ? 'block' : 'none'}` }}>
                        <LgPaginationA
                            total={Math.ceil(listTotal / 12)}
                            size="normal"
                            currentPage={currentIndex}
                            onChangePage={(pageIndex) => {
                                setCurrentIndex(pageIndex);
                            }}
                        ></LgPaginationA>
                    </div>
                    {/* <ConfigProvider locale={zhCN}>
                        <Pagination
                            className="table_pagination"
                            total={Number(listTotal ? listTotal : 0)}
                            current={currentIndex}
                            pageSize={12}
                            showQuickJumper={false}
                            showSizeChanger={false}
                            hideOnSinglePage
                            onChange={(pageIndex) => {
                                setCurrentIndex(pageIndex);
                            }} />
                    </ConfigProvider> */}
                </div>
            </Spin >
            <ModalBox className="modalBox" css={{
                display: modalVisible ? '' : 'none'
            }}>
                <ModalCard>
                    <ModalHeader>添加日程</ModalHeader>
                    <CloseBtn onClick={() => setModalVisible(false)} />
                    <ModalOption>
                        <span className="option_name">日程标题:</span>
                        <div className="schedule_title">
                            <LgInput
                                type='text'
                                width={400}
                                value={modalInfo.scheduleTitle || ''}
                                onChange={(e) => editModalInfo("scheduleTitle", e.target.value.substring(0, 30))}
                                maxLength={30}
                            />
                            <span className="number_tip">{`${modalInfo.scheduleTitle ? modalInfo.scheduleTitle.length : 0}/30`}</span>
                        </div>
                    </ModalOption>
                    <ModalOption>
                        <span className="option_name">时间:</span>
                        <span className='option_startDate'>
                            <DatePicker
                                className='option_date'
                                placeholder="请选择"
                                locale={locale}
                                size={12}
                                value={moment(modalInfo.scheduleDate)}
                                onChange={(value) => editModalInfo("scheduleDate", value)}
                            />
                            <LgDatePicker
                                className='option_time'
                                type="C"
                                start="00:00"
                                step="00:15"
                                end="23:45"
                                value={new Date(dayjs(modalInfo.scheduleDate).format("YYYY-MM-DD") + " " + modalInfo.startTime)}
                                onChange={(value) => { editModalInfo('startTime', dayjs(value).format('HH:mm'), true) }}
                            />
                        </span>
                        <span className='date_slice'></span>
                        <span className='option_endDate'>
                            <DatePicker
                                className='option_date'
                                placeholder="请选择"
                                locale={locale}
                                value={moment(modalInfo.scheduleDate)}
                                onChange={value => editModalInfo("scheduleDate", value)}
                            />
                            <LgDatePicker
                                className='option_time'
                                type="C"
                                start="00:00"
                                step="00:15"
                                end="23:45"
                                value={new Date(dayjs(modalInfo.scheduleDate).format("YYYY-MM-DD") + " " + modalInfo.endTime)}
                                onChange={(value) => { editModalInfo('endTime', dayjs(value).format('HH:mm')) }}
                            />
                        </span>
                        {/* <DatePicker
                            className="modal_datepicker"
                            locale={locale}
                            disabledDate={(current) => current < moment().endOf('day') || current > moment(userInfo.termEndDate).startOf("day")}
                            value={modalInfo.scheduleDate ? moment(modalInfo.scheduleDate) : moment(new Date())}
                            onChange={(value) => editModalInfo("scheduleDate", value)}
                            getPopupContainer={(trigger) => trigger.parentElement}
                        />
                        <RangePicker
                            locale={locale}
                            order={false}
                            value={modalInfo.startTime ? [moment(modalInfo.scheduleDate + " " + modalInfo.startTime), moment(modalInfo.scheduleDate + " " + modalInfo.endTime)] : [moment(getDataInt(), 'HH:mm'), moment(getDataInt(2), 'HH:mm')]}
                            className="modal_timepicker"
                            format="HH:mm"
                            disabledHours={(current) => { console.log(current) }}
                            onChange={(value) => editModalInfo("scheduleTime", value)}
                        // getPopupContainer={(trigger) => trigger.parentElement}
                        /> */}
                    </ModalOption>
                    <div css={{ padding: '0 24px' }}>
                        <Collapse
                            defaultActiveKey={showMoreSetting ? ['1'] : null}
                            onChange={() => setShowMoreSetting(!showMoreSetting)}
                            expandIconPosition={'right'}
                            activeKey={showMoreSetting ? "1" : ''}
                            className="showMore_setting"
                        >
                            <Panel header='高级设置' key="1">
                                <ModalOption className="modal_option schedule_location">
                                    <span className="option_name">地点:</span>
                                    <LgInput
                                        type='text'
                                        className="location_input"
                                        maxLength={50}
                                        placeholder=""
                                        value={modalInfo.scheduleLocation}
                                        onChange={(e) => editModalInfo("scheduleLocation", e.target.value)} />
                                </ModalOption>
                                <ModalOption className="schedule_remark">
                                    <span className="option_name">日程描述:</span>
                                    <div className="schedule_content">
                                        <LgTextarea
                                            className='textarea-warp'
                                            textarea={{
                                                onInput: (e) => editModalInfo("scheduleContent", e.target.value.substring(0, 200)),
                                                maxLength: 200,
                                                value: modalInfo.scheduleContent || ''
                                            }}
                                        ></LgTextarea>
                                        <span className="number_tip">{`${modalInfo.scheduleContent ? modalInfo.scheduleContent.length : 0}/200`}</span>
                                    </div>
                                </ModalOption>
                                <ModalOption className="modal_option">
                                    <span className="option_name">日程提醒:</span>
                                    <LgSelect
                                        key={'timeSlelect'}
                                        value={modalInfo.remindTime.text || '开始前30分钟'}
                                        datalist={remindTime}
                                        btnType={2}
                                        width={130}
                                        ref={timeSelect}
                                        SelectOption={setRemindHandle}
                                    ></LgSelect>
                                </ModalOption>
                            </Panel>
                        </Collapse>
                    </div>
                    <ModalFooter>
                        <LgButton backgroundType='opacification' type='info' onClick={handleSchedule}>确认</LgButton>
                        <LgButton backgroundType='translucent' border type='info' onClick={() => setModalVisible(false)}>取消</LgButton>
                    </ModalFooter>
                </ModalCard>
            </ModalBox>

        </div >
    )
}
// const mapProps = (state) => {
//     return {
//         userInfo: state.userInfo,
//         sysAddrInfo: state.sysAddrInfo,
//         currentIdentity: state.currentIdentity,
//         sysInfo: state.sysInfo,
//         alertInfo: state.alertInfo,
//         mainServer: state.mainServer,
//         officeUrl: state.officeUrl,
//         isEdu:state.isEdu
//     }
// }
// export default connect(mapProps)(Todo);
export default Todo;

const popShow = keyframes`
    0%{
        transform:scale(0) translate(-50%,-50%);
        opacity:.4;
    }

    100%{
        transform:scale(1) translate(-50%,-50%);
        opacity:1;
    }
`

const ModalBox = styled.div`
    position:fixed;
    left: 0;
    top:0;
    width: 100vw;
    height: 100vh;
    background-color: rgba(0,0,0,.3);
`

const ModalCard = styled.div`
    position:absolute;
    top:50%;
    left:50%;
    width: 784px;
    background-color: #fff;
    border-radius: 3px;
    box-shadow: 0px 0px 12px 0px rgba(0, 0, 0, 0.16);
    transform:translate(-50%,-50%);
    transform-origin:left center;
    animation:${popShow} .2s linear ;
`

const ModalHeader = styled.div`
    height: 50px;
    line-height: 50px;
    position: relative;
    padding:0 16px;
    font-weight:700;
`

const ModalOption = styled.div`
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    &:nth-child(1){
        text-align: end;
        margin-right: 8px;
        white-space: nowrap;
        color: #666;
    }
    &:nth-child(2){
        position:relative;
    }

`

const CloseBtn = styled.i`
    display:inline-block;
    width: 14px;
    height: 14px;
    position: absolute;
    right: 16px;
    top: 19px;
    cursor: pointer;
    background-image:url(${CloseIcon});
    background-size: contain;
`

const ModalFooter = styled.div`
  display:flex;
  align-items:center;
  justify-content:space-between;
  padding:0 315px;
  height: 70px;
  

`

